package sdk

import (
	"context"
	"fmt"
	"gim-server/config"
	"gim-server/utils"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"sync"
	"time"
)

var (
	db     *gorm.DB
	dbOnce sync.Once
)

func DB(ctx context.Context) *gorm.DB {
	dbOnce.Do(func() {
		var (
			err error
			cfg = config.GetCfg()
		)
		if cfg.DBType == "mysql" {
			cfg.MysqlPass, err = utils.AesDe(cfg.MysqlPass, cfg.SignKey)
			if err != nil {
				panic(fmt.Errorf("解密mysql密码(%v)错误！", cfg.MysqlPass))
			}
			url := fmt.Sprintf(cfg.MysqlUrl, cfg.MysqlUser, cfg.MysqlPass, cfg.MysqlDB)
			db, err = gorm.Open(mysql.Open(url), &gorm.Config{
				Logger: logger.Default,
			})
		} else {
			cfg.MysqlPass, err = utils.AesDe(cfg.PgPass, cfg.SignKey)
			if err != nil {
				panic(fmt.Errorf("解密pg密码(%v)错误！", cfg.PgPass))
			}
			url := fmt.Sprintf(cfg.PgUrl, cfg.PgUser, cfg.PgPass, cfg.PgDB)
			db, err = gorm.Open(postgres.Open(url), &gorm.Config{
				Logger: logger.Default,
			})
		}
		if err != nil {
			panic(err)
		}
		sqlDB, err := db.DB()
		if err != nil {
			panic(err)
		}
		sqlDB.SetMaxOpenConns(10)
		sqlDB.SetMaxOpenConns(100)
		sqlDB.SetConnMaxLifetime(time.Hour)
	})
	return db.WithContext(ctx)
}
